<template>
  <div class="wrap">
    <!-- 面包屑 -->
    <bread></bread>
    <div class="content">
      <!-- 搜素 -->
      <el-input
        class="inp"
        placeholder="请输入内容"
        @clear="getUserList"
        v-model="queryInfo.query"
        clearable
      ></el-input>
      <el-button icon="el-icon-search" type="info" @click="getUserList"></el-button>
      <!-- 添加功能 -->
      <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
      <!-- 渲染数据 -->
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column fixed prop="id" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="create_time" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column width="200px" label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 角色按钮 -->
            <el-tooltip effect="dark" content="分配角色">
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-s-tools"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination
        style="margin-top:20px;"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
        <el-form :model="addForm" :rules="addFormRules" ref="addFromRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item type="password" label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户对话框 -->
      <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
      >
        <el-form :model="editFrom" :rules="editFromRef" ref="editFromRef" label-width="70px">
          <el-form-item label="用户名">
            <el-input v-model="editFrom.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editFrom.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editFrom.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog
        title="分配角色"
        :visible.sync="setRoleDialogVisible"
        width="50%"
        @close="setRoleDialogColsed"
      >
        <div>
          <p>当前的用户:{{userInfo.username}}</p>
          <p>当前的角色:{{userInfo.role_name}}</p>
          <p>
            分配新角色:
            <el-select v-model="selectedRoleId" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import bread from "../bread";
import API from "../API/Api";
export default {
  name: "",
  data() {
    var checkEmail = (rule, value, callback) => {
      var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (reg.test(value)) {
        // 格式正确返回true
        callback();
      } else {
        // 格式不正确
        return callback(new Error("邮箱格式不对"));
      }
    };
    //手机验证
    var checkMobile = (rule, value, callback) => {
      var mobileReg = /^1[3456789]\d{9}$/;
      if (mobileReg.test(value)) {
        // 格式正确返回true
        callback();
      } else {
        // 格式不正确
        return callback(new Error("手机号格式不对"));
      }
    };
    return {
      inp: "",
      queryInfo: {
        query: "",
        // 当前第几页
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      // 数据列表
      tableData: [],
      // 对话框显示隐藏
      addDialogVisible: false,
      // 添加用户表单数据
      addForm: {},
      // 校验
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 5 到 15 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      // 修改用户对话框显示隐藏
      editDialogVisible: false,
      editFrom: {},
      // 修改表单验证规则对象
      editFromRef: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      setRoleDialogVisible: false,
      userInfo: {},
      rolesList: [],
      selectedRoleId: ""
    };
  },
  mounted() {
    this.getUserList();
  },
  methods: {
    // 渲染数据区域
    getUserList(queryInfo) {
      API.getUserList(this.queryInfo).then(res => {
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error("获取信息失败");
        } else {
          // this.$message.success(res.meta.msg);
          console.log(res.data);
          this.tableData = res.data.users;
          this.total = res.data.total;
          console.log(res);
        }
      });
    },
    // 分页区域
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    // 开关改变
    userStateChanged(userinfo) {
      API.userStateChanged(userinfo.id, userinfo.ms_state).then(res => {
        console.log(res);
        if (res.meta.status !== 200) {
          userinfo.ms_state = !userinfo.ms_state;
          return this.$message.error("更新用户状态失败");
        }
        this.$message.success("更新用户状态成功");
      });
    },
    // 弹出框
    open() {
      this.$alert("这是一段内容", "标题名称", {
        confirmButtonText: "确定",
        callback: action => {
          this.$message({
            type: "info",
            message: `action: ${action}`
          });
        }
      });
    },
    // 对话框关闭事件
    addDialogClosed() {
      this.$refs.addFromRef.resetFields();
    },
    // 添加数据
    addUser() {
      this.$refs.addFromRef.validate(async valid => {
        console.log(valid);
        if (!valid) return;
        API.addUser(this.addForm).then(res => {
          console.log(res);
          if (res.meta.status !== 201) {
            return this.$message.error("添加用户失败");
          }
          this.$message.success("添加用户成功");
          this.addDialogVisible = false;
          this.getUserList();
        });
      });
    },
    // 编辑用户对话框
    showEditDialog(id) {
      API.showEditDialog(id).then(res => {
        console.log(res);
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg);
        }
        this.editFrom = res.data;
        this.editDialogVisible = true;
      });
    },
    // 修改用户对话框关闭事件
    editDialogClosed() {
      this.$refs.editFromRef.resetFields();
    },
    // 修改用户信息提交
    editUserInfo() {
      this.$refs.editFromRef.validate(async valid => {
        if (!valid) return;
        API.editUserInfo(
          this.editFrom.id,
          this.editFrom.email,
          this.editFrom.mobile,
        ).then(res => {
          console.log(res);
          if (res.meta.status !== 200) {
            return this.$message.success(res.meta.msg);
          }
          this.editDialogVisible = false;
          this.getUserList();
          this.$message.success(res.meta.msg);
        });
      });
    },
    // 删除功能
    async removeUserById(id) {
      const confrimResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      console.log(confrimResult);
      if (confrimResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      API.removeUserById(id).then(res => {
        if (res.meta.status !== 200) {
          return this.$message.error("删除失败");
        }
        this.$message.success("删除成功");
        this.getUserList();
      });
    },
    // 展示分配角色的对话框
    setRole(userInfo) {
      this.userInfo = userInfo;
      API.setRole().then(res => {
        if (res.meta.status !== 200) {
          return this.$message.error("获取角色列表失败");
        }
        this.rolesList = res.data;
      });
      this.setRoleDialogVisible = true;
    },
    saveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error("请选择要分配的角色");
      }
      API.saveRoleInfo(this.userInfo.id,this.selectedRoleId)
        .then(res => {
          console.log(res);
          if (res.meta.status !== 200) {
            return this.$message.error("更新角色失败");
          }
          this.$message.success("更新角色成功");
          this.getUserList();
          this.setRoleDialogVisible = false;
        });
    },
    setRoleDialogColsed() {
      this.selectedRoleId = "";
      this.userInfo = {};
    }
  },
  computed: {},
  components: {
    bread
  },
  watch: {},
  getters: {}
};
</script>

<style scoped>
.wrap {
  width: 100%;
  margin-left: 10px;
}
.content {
  width: 88%;
  height: 90%;
  margin-top: 10px;
  background: #fff;
  padding-top: 20px;
  padding-left: 20px;
  box-sizing: border-box;
  overflow: auto;
}
.inp {
  width: 400px;
}
</style>